package edu.ctbu.ljy.bot.util;

import edu.ctbu.ljy.bot.constain.ConversationConfig;
import edu.ctbu.ljy.bot.constain.RoleContent;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

import java.io.IOException;
import java.util.List;

public class MyWebSocketListener extends WebSocketListener {
    public MyWebSocketListener(ConversationConfig res){
        this.res=res;
    }
    ConversationConfig res;
    //private Boolean wsCloseFlag = true;
    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        System.out.print("对话进行中！！！！");
        ConversationThread myThread = new ConversationThread(webSocket,res);
        myThread.start();
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        // System.out.println(userId + "用来区分那个用户的结果" + text);
        JsonParse myJsonParse = res.gson.fromJson(text, JsonParse.class);
        if (myJsonParse.header.code != 0) {
            System.out.println("发生错误，错误码为：" + myJsonParse.header.code);
            System.out.println("本次请求的sid为：" + myJsonParse.header.sid);
            webSocket.close(1000, "");
            res.wsCloseFlag = true;
        }
        List<Text> textList = myJsonParse.payload.choices.text;
        for (Text temp : textList) {
            System.out.print(temp.content);
            res.totalAnswer = res.totalAnswer+temp.content;
        }
        if (myJsonParse.header.status == 2) {
            // 可以关闭连接，释放资源
            System.out.println();
            System.out.println("*************************************************************************************");
            if(canAddHistory(res)){
                RoleContent roleContent=new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(res.totalAnswer);
                res.historyList.add(roleContent);
            }else{
                res.historyList.remove(0);
                RoleContent roleContent=new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(res.totalAnswer);
                res.historyList.add(roleContent);
            }
            res.wsCloseFlag = true;
        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        try {
            if (null != response) {
                int code = response.code();
                System.out.println("onFailure code:" + code);
                System.out.println("onFailure body:" + response.body().string());
                if (101 != code) {
                    System.out.println("connection failed");
                    System.exit(0);
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static boolean canAddHistory(ConversationConfig res){  // 由于历史记录最大上线1.2W左右，需要判断是能能加入历史
        int history_length=0;
        for(RoleContent temp:res.historyList){
            history_length=history_length+ temp.content.length();
        }
        if(history_length>12000){
            res.historyList.remove(0);
            res.historyList.remove(1);
            res.historyList.remove(2);
            res.historyList.remove(3);
            res.historyList.remove(4);
            return false;
        }else{
            return true;
        }
    }

    class JsonParse {
        Header header;
        Payload payload;
    }

    class Header {
        int code;
        int status;
        String sid;
    }

    class Payload {
        Choices choices;
    }

    class Choices {
        List<Text> text;
    }

    class Text {
        String role;
        String content;
    }
}